<template>
  <!--列表-->
  <router-exact-view name="term">
    <div style="width: 100%" class="template-list-page-container">
      <my-table
        v-loading="loading"
        :columns="columns"
        :data-source="data"
        :pagination="pagination"
        :btn-options="btnOptions"
        title="学期列表"
        @page-change="handlePageChange"
      >
        <div slot="table-btn">
          <el-button type="primary" @click="addTerm">新增学期</el-button>
        </div>
      </my-table>
    </div>
    <el-dialog :title="title" :visible.sync="dialogFormVisible">
      <el-form ref="addForm" :model="form">
        <el-form-item label="学期" :label-width="formLabelWidth">
          <el-input v-model="form.name" autocomplete="off" />
        </el-form-item>
        <el-form-item label="学期起止时间" :label-width="formLabelWidth">
          <el-date-picker
            v-model="form.termRange"
            style="margin-bottom: 10px;"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button
          type="primary"
          @click="submitTerm"
        >确 定</el-button>
      </div>
    </el-dialog>
  </router-exact-view>
</template>

<script>
import moment from 'moment'
import { getTerm, getTermDetail, addTerm, startTerm, endTerm } from '@/api/basic'
import MyTable from '@/components/my-table/index'
import RouterExactView from '@/components/routerExactView'
import { schoolYearColumns } from '../columns'

export default {
  components: { RouterExactView, MyTable },
  data() {
    const that = this
    return {
      /* 列表相关 */
      columns: schoolYearColumns,
      data: [],
      pagination: {
        current: 1,
        pageSize: 10,
        total: 0
      },
      btnOptions: [
        {
          name: '编辑',
          handler: function(row) {
            that.getTermDetail(row.id)
          }
        },
        {
          name: '开始学期',
          v_if: row => row.status === 0,
          handler: function(row) {
            that.startTerm(row.id)
          }
        },
        {
          name: '结束学期',
          v_if: row => row.status === 1,
          handler: function(row) {
            that.endTerm(row.id)
          }
        }
      ],
      // 新增编辑学年的弹窗
      dialogFormVisible: false,
      form: {
        name: '',
        isSure1: 1,
        isSure2: 1
      },
      formLabelWidth: '150px',
      loading: false,
      title: '新增学期'
    }
  },
  mounted() {
    if (this.$route.name === 'term') {
      this.handlePageChange()
    }
  },
  methods: {
    async handlePageChange(current, size) {
      if (current) {
        this.pagination.current = current
      }
      if (size) {
        this.pagination.pageSize = size
      }
      this.loading = true
      try {
        const res = await getTerm({
          pageNum: this.pagination.current,
          pageSize: this.pagination.pageSize
        })
        if (res && res.list && res.list.length) {
          this.data = res.list
          this.pagination = {
            current: res.pageNum,
            pageSize: res.pageSize,
            total: res.totalElements
          }
        }
        this.loading = false
      } catch (err) {
        this.loading = false
      }
    },
    resetSearchForm() {
      this.searchForm = {}
      this.handlePageChange(1)
    },
    addTerm() {
      this.form = {}
      this.dialogFormVisible = true
    },
    submitTerm() {
      const that = this
      const { form } = this
      this.$refs['addForm'].validate((valid) => {
        if (valid) {
          const params = JSON.parse(JSON.stringify(that.form))
          if (form.termRange) {
            params.termStart = moment(form.termRange[0]).format('YYYY-MM-DD')
            params.termEnd = moment(form.termRange[1]).format('YYYY-MM-DD')
          }
          delete params.termRange
          params.schoolId = 1
          addTerm(params).then((res) => {
            if (res) {
              that.$message({
                message: '新增学期成功！',
                type: 'success'
              })
              that.dialogFormVisible = false
              that.handlePageChange(that.pagination.current)
            }
          })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    async getTermDetail(id) {
      try {
        const res = await getTermDetail({
          id: Number(id)
        })
        if (res) {
          this.form = JSON.parse(JSON.stringify(res))
          this.$set(this.form, 'termRange', [
            new Date(res.termStart),
            new Date(res.termEnd)
          ])
          this.dialogFormVisible = true
        }
      } catch (err) {
        console.log('接口出错')
      }
    },
    startTerm(id) {
      const that = this
      this.$confirm(`该操作将把该学期设为当前学期，如果是新学年，将会把所有学生年级加1，所有9年级学生设置为毕业状态，请谨慎操作！`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消'
      }).then(async() => {
        try {
          const res = await startTerm({
            id
          })
          if (res) {
            that.$message({
              message: `开始学期成功！`,
              type: 'success'
            })
            that.handlePageChange(that.pagination.current)
          }
        } catch (err) {
          console.log('接口出错', err)
          that.$message.error(err.desc)
        }
      }).catch(() => {
        console.log('取消')
      })
    },
    endTerm(id) {
      const that = this
      this.$confirm(`该操作将结束当前学期，并对当前学期的送教任务进行打分。另外，在设置新的生效学期前，不能再新建送教任务及送教提报，请谨慎操作！`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消'
      }).then(async() => {
        try {
          const res = await endTerm({
            id
          })
          if (res) {
            that.$message({
              message: `结束学期成功！`,
              type: 'success'
            })
            that.handlePageChange(that.pagination.current)
          }
        } catch (err) {
          that.$message.error(err.desc)
        }
      }).catch(() => {
        console.log('取消')
      })
    }
  }
}
</script>
<style scoped lang="less">
@import "../../common.css";
/* 查询条件容器的样式 */
.search-area {
  padding: 16px 16px 0;
  margin-bottom: 8px;
  background: #fff;
}
</style>
